cin >>type 循环中执行怎么被跳过了??

来源:百度知道 编辑:UC知道 时间:2024/05/31 07:22:01
#include<iostream.h>
const int len=10;
int len1=5,len2=50;
int FreeSeatNum(int* a,int b,int c);//空余作座位数
int FreeSeat(int* aa,int bb,int cc);//购票
void main()
{
int seat[len]={0};
int type;
while(1)
{
cout<<"Smoking seat left:"<<FreeSeatNum(&seat[0], 0, len1-1)<<endl;
cout<<"Nonsmoking seat left:"<<FreeSeatNum(&seat[len1], len1, len-1)<<endl;
cout<<"Please type 1 for 'smoking'"<<endl<<"Please type 2 for 'nonsmoking'"<<endl;
cin>>type;
if(type==1)//有烟区
{
int i,s;
i=FreeSeat( &seat[0], 0, len1-1);
if(i==-1)
{
{
cout<<"If you want the nonsmoking area ?"
<<"Y or N"
<<endl;
cin>>s;
i=FreeSeat( &seat[le

在cin>>type和cin>>s时,由于type和s定义为一个整型变量,如果我们输入一个字符就会导致刷屏的结果,这是因为非数字字符无法被cin接收而一直停留在缓冲区,导致下一次cin时直接从缓存读数但字符无法读取结果,引发死循环。
解决方法:
将s,type定义为字符型变量(char),
将if(type==1)和if(type==2)语句改为
if(type=='1')
if(type=='2')

在cin>>type; 前面加上:
fflush( stdin );
cin.clear();